package com.example.sistemacompras;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.sql.Date;
import java.text.SimpleDateFormat;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.sistemacompras.db.DatabaseHandler;
import com.example.sistemacompras.entity.Client;
import com.example.sistemacompras.utils.Utils;

public class UserSiginActivity extends Activity {

	private EditText nomeDeUsuarioU;

	private EditText EmailU;

	private Bitmap fotoU = null;

	private ImageView fotoIV = null;

	private Uri fileUri = null;

	private static final int CAPTURE_IMAGE_ACTIVITY_REQ = 0;

	private EditText passwordU;

	private String mCurrentPhotoPath;

	private DatabaseHandler db;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_user_sigin);
		if (db == null) {
			db = new DatabaseHandler(getApplicationContext());
		}
		nomeDeUsuarioU = (EditText) findViewById(R.id.nome_edit);
		nomeDeUsuarioU.setText("");
		EmailU = (EditText) findViewById(R.id.email_edit);
		EmailU.setText("");
		passwordU = (EditText) findViewById(R.id.password_edit);
		passwordU.setText("");
		fotoIV = (ImageView) findViewById(R.id.user_photo);
		fotoIV.setImageDrawable(getResources().getDrawable(R.drawable.images));
		mCurrentPhotoPath = null;
	}
	
	 @Override 
	protected void onSaveInstanceState(Bundle outState) {
	}

	public void cadastrarUsuario(View view) {
		String nomeP = nomeDeUsuarioU.getText().toString();
		String emailP = EmailU.getText().toString();
		String passwordP = passwordU.getText().toString();
		Client person = new Client();
		person.setEmail(emailP);
		person.setName(nomeP);
		person.setPassword(passwordP);
		if (fotoIV != null) {
			Utils util = new Utils(this);
			int proportion = 6;
			int width = util.getWidthInPixels() / proportion;
			int height = util.getHeightInPixels() / proportion;
			fotoU = getResizedBitmap(
					(Bitmap) ((BitmapDrawable) fotoIV.getDrawable())
							.getBitmap(),
					width, height);

			person.setPhoto(fotoU);
		}

		boolean teste = db.createClient(person);

		Intent returnIntent = new Intent();
		returnIntent.putExtra("cadastro", teste);
		setResult(RESULT_OK, returnIntent);
		finish();
	}

	static final int REQUEST_TAKE_PHOTO = 1;

	@SuppressLint("SimpleDateFormat")
	private File createImageFile() throws IOException {
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
				.format(new Date(0));
		String imageFileName = "JPEG_" + timeStamp + "_";
		File storageDir = Environment
				.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
		File image = File.createTempFile(imageFileName, /* prefix */
				".jpg", /* suffix */
				storageDir /* directory */
		);
		try {
			mCurrentPhotoPath = getPath(this,
					Uri.parse(image.toURI().toString()));

		} catch (URISyntaxException e) {
			e.printStackTrace();
		}

		return image;
	}

	public void shootPhoto(View view) {
		Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		fileUri = Uri.fromFile(getOutputPhotoFile());
		i.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
		startActivityForResult(i, CAPTURE_IMAGE_ACTIVITY_REQ);
	}

	private File getOutputPhotoFile() {
		File directory = new File(
				Environment
						.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
				getPackageName());
		if (!directory.exists()) {
			if (!directory.mkdirs()) {

				return null;
			}
		}
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
				.format(new Date(0));
		return new File(directory.getPath() + File.separator + "IMG_"
				+ timeStamp + ".jpg");
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQ) {
			if (resultCode == RESULT_OK) {
				Uri photoUri = null;
				if (data == null) {
					Toast.makeText(this, "Image saved successfully",
							Toast.LENGTH_LONG).show();
					photoUri = fileUri;
				} else {
					photoUri = data.getData();
					Toast.makeText(this,
							"Image saved successfully in: " + data.getData(),
							Toast.LENGTH_LONG).show();
				}
				showPhoto(photoUri);
			} else if (resultCode == RESULT_CANCELED) {
				Toast.makeText(this, "Cancelled", Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(this, "Callout for image capture failed!",
						Toast.LENGTH_LONG).show();
			}
		}
	}

	private void showPhoto(Uri photoUri) {

		File imageFile = new File(photoUri.getEncodedPath());
		if (imageFile.exists()) {
			Drawable oldDrawable = fotoIV.getDrawable();
			Utils util = new Utils(this);
			int proportion = 6;
			int width = util.getWidthInPixels() / proportion;
			int height = util.getHeightInPixels() / proportion;
			fotoU = getResizedBitmap(
					BitmapFactory.decodeFile(imageFile.getAbsolutePath()),
					width, height);
//			fotoU = Utils.rotateBitmap(imageFile.getAbsolutePath(),fotoU);
			if (oldDrawable != null) {
				((BitmapDrawable) oldDrawable).getBitmap().recycle();
			}
			BitmapDrawable drawable = new BitmapDrawable(this.getResources(),
					fotoU);
			fotoIV.setScaleType(ImageView.ScaleType.FIT_CENTER);
			fotoIV.setImageDrawable(drawable);

		}
	}

	public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {

		int width = bm.getWidth();

		int height = bm.getHeight();

		float scaleWidth = ((float) newWidth) / width;

		float scaleHeight = ((float) newHeight) / height;

		Matrix matrix = new Matrix();

		matrix.postScale(scaleWidth, scaleHeight);
		matrix.postRotate(90.0f);

		Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height,
				matrix, false);

		return resizedBitmap;

	}

	public static String getPath(Context context, Uri uri)
			throws URISyntaxException {
		if ("content".equalsIgnoreCase(uri.getScheme())) {
			String[] projection = { "_data" };
			Cursor cursor = null;

			try {
				cursor = context.getContentResolver().query(uri, projection,
						null, null, null);
				int column_index = cursor.getColumnIndexOrThrow("_data");
				if (cursor.moveToFirst()) {
					return cursor.getString(column_index);
				}
			} catch (Exception e) {
				// Eat it
			}
		} else if ("file".equalsIgnoreCase(uri.getScheme())) {
			return uri.getPath();
		}

		return null;
	}

	public void enviarUsuario(View view) {
		String nome = String.valueOf(nomeDeUsuarioU.getText());
		String email = String.valueOf(EmailU.getText());
		String senha = String.valueOf(passwordU.getText());
		if ((nome != null && nome != "") && (email != null && email != "")
				&& (senha != null && senha != "")) {
			EditText number = (EditText) findViewById(R.id.phone_number);
			String sms = "cadastro;" + nome + ";" + email + ";" + senha;
			Intent smsIntent = new Intent(Intent.ACTION_VIEW);
			smsIntent.setType("vnd.android-dir/mms-sms");
			smsIntent.putExtra("address", String.valueOf(number.getText()));
			smsIntent.putExtra("sms_body", sms);
			startActivity(smsIntent);
		}
	}
}
